import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { ICurrentUser } from '@nbase/shared';

/**
 * 获取当前登录用户装饰器
 *
 * @example
 * // 用户ID
 * async getProfile(@CurrentUserId() userId: string) { ... }
 *
 */
export const CurrentUserId = createParamDecorator(
  (_data: string, ctx: ExecutionContext): string | undefined => {
    const request = ctx.switchToHttp().getRequest();

    // 从 request.user 获取
    // request.user 由 JwtStrategy.validate() 设置
    const user: ICurrentUser | undefined = request.user;

    if (!user) {
      return undefined;
    }

    return user.userId;
  }
);

